<template>
  <div class="user-profile-detail">
    <!-- 添加 header 组件 -->
    <header-component />
    <!-- 页面标题 -->
    <el-page-header @back="handleBack" :content="pageTitle">
    </el-page-header>

    <el-card class="profile-card" style="margin-top: 20px;">
      <el-row :gutter="20">
        <!-- 左侧基本信息区域 -->
        <el-col :span="16">
          <el-form ref="profileForm" :model="formData" label-width="120px" :rules="formRules" class="profile-form">
            <!-- 基本信息分组 -->
            <el-form-item label="用户信息" prop="" class="form-section-title">
              <el-divider content-position="left" class="custom-divider">基本信息</el-divider>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="formData.username" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="formData.nickname" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-input v-model="genderDisplay" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期" prop="birth_date">
                  <el-input v-model="formData.birth_date" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 身体指标分组 -->
            <el-form-item label="身体指标" prop="" class="form-section-title">
              <el-divider content-position="left">身体指标</el-divider>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="身高(cm)" prop="height">
                  <el-input v-model="formData.height" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="体重(kg)" prop="weight">
                  <el-input v-model="formData.weight" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="BMI" prop="">
                  <el-input v-model="bmiValue" disabled placeholder="自动计算" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="BMI分类" prop="">
                  <el-input v-model="bmiCategory" disabled placeholder="自动计算" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 健身信息分组 -->
            <el-form-item label="健身信息" prop="" class="form-section-title">
              <el-divider content-position="left">健身信息</el-divider>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="健身目标" prop="fitness_goal">
                  <el-input v-model="fitnessGoalDisplay" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="健身水平" prop="fitness_level">
                  <el-input v-model="fitnessLevelDisplay" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="活动水平" prop="activity_level">
                  <el-input v-model="activityLevelDisplay" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="饮食偏好" prop="dietary_preference">
                  <el-input v-model="dietaryPreferenceDisplay" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="偏好训练时长(分钟)" prop="preferred_workout_duration">
                  <el-input v-model="formData.preferred_workout_duration" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="每周训练次数" prop="preferred_workout_times">
                  <el-input v-model="formData.preferred_workout_times" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 健康信息分组 -->
            <el-form-item label="健康信息" prop="" class="form-section-title">
              <el-divider content-position="left">健康信息</el-divider>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="糖尿病" prop="has_diabetes">
                  <el-input v-model="hasDiabetesDisplay" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="高血压" prop="has_hypertension">
                  <el-input v-model="hasHypertensionDisplay" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="心脏病" prop="has_heart_disease">
                  <el-input v-model="hasHeartDiseaseDisplay" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="食物过敏" prop="food_allergies">
              <el-input v-model="formData.food_allergies" type="textarea" :rows="3" disabled />
            </el-form-item>

            <el-form-item label="其他饮食限制" prop="dietary_restrictions">
              <el-input v-model="formData.dietary_restrictions" type="textarea" :rows="3" disabled />
            </el-form-item>

                         <!-- 操作按钮 -->
             <el-form-item>
               <el-button @click="handleBack">返回</el-button>
               <el-button type="primary" @click="handleEdit" v-if="!hasRouteParams">编辑资料</el-button>
             </el-form-item>
          </el-form>
        </el-col>

        <!-- 右侧信息和LOGO区域 -->
        <el-col :span="8">
          <el-card class="info-card">
            <div slot="header" class="card-header">用户信息概览</div>

            <div class="avatar-container">
              <el-avatar :size="100" class="user-avatar">
                <img v-if="formData.avatar" :src="formData.avatar" alt="用户头像">
                <span v-else>{{ formData.nickname?.substring(0, 2) || '用户' }}</span>
              </el-avatar>
              <el-form-item label="头像URL">
                <el-input v-model="formData.avatar" disabled />
              </el-form-item>
            </div>

            <div class="calculated-data">
              <p><strong>年龄:</strong> {{ ageValue || '未设置' }}</p>
              <p><strong>基础代谢率(BMR):</strong> {{ bmrValue || '无法计算' }} 卡路里/天</p>
              <p><strong>每日总消耗(TDEE):</strong> {{ tdeeValue || '无法计算' }} 卡路里/天</p>
              <p><strong>每日目标卡路里:</strong> {{ calorieTarget || '无法计算' }} 卡路里/天</p>
              <p><strong>创建时间:</strong> {{ formData.created_at || '未知' }}</p>
              <p><strong>最后更新:</strong> {{ formData.updated_at || '未知' }}</p>
            </div>

            <!-- 专属LOGO区域 -->
            <el-divider content-position="left" class="custom-divider">专属LOGO</el-divider>
            <div class="logo-container">
              <div v-if="formData.logo_url" class="logo-preview">
                <div class="real-logo">
                  <img :src="formData.logo_url" alt="专属LOGO" class="logo-image" />
                </div>
                <p class="logo-desc">专属LOGO预览</p>
                <el-button size="small" type="primary" @click="downloadLogo" style="margin-top: 10px;">
                  下载LOGO
                </el-button>
                <el-button size="small" type="warning" @click="regenerateLogo" style="margin-top: 10px; margin-left: 10px;">
                  重新生成
                </el-button>
              </div>
              <div v-else-if="logoGenerated" class="logo-preview">
                <div class="fake-logo">
                  <span class="logo-initial">{{ formData.nickname?.substring(0, 1) || 'U' }}</span>
                </div>
                <p class="logo-desc">{{ logoMessage || 'LOGO生成中，请稍候...' }}</p>
                
                <!-- 进度条 -->
                <div class="logo-progress" v-if="logoProgress > 0 && logoProgress < 100">
                  <el-progress 
                    :percentage="logoProgress" 
                    :status="logoStatus === 'error' ? 'exception' : undefined"
                    :stroke-width="8"
                    :show-text="true"
                    :format="(percentage) => `${percentage}%`"
                  />
                </div>
                
                <!-- 状态指示器 -->
                <div class="logo-status" v-if="logoStatus">
                  <el-tag 
                    :type="logoStatus === 'success' ? 'success' : logoStatus === 'error' ? 'danger' : 'info'"
                    size="small"
                  >
                    {{ logoStatus === 'success' ? '成功' : logoStatus === 'error' ? '失败' : '处理中' }}
                  </el-tag>
                </div>
              </div>
              <div v-else class="logo-placeholder">
                <p>点击下方按钮生成专属LOGO</p>
                <p style="font-size: 12px; color: #909399; margin-top: 5px;">
                  基于您的性别和健身水平生成个性化LOGO
                </p>
              </div>

              <el-button 
                style="width: 100%; margin-top: 15px;" 
                type="success" 
                :icon="loading ? 'el-icon-loading' : 'el-icon-picture-outline'"
                :loading="loading"
                :disabled="loading"
                @click="generateLogo">
                {{ loading ? '生成中...' : '生成专属LOGO' }}
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, computed, ref, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import axios from 'axios'
import HeaderComponent from '@/components/header.vue'

// Logo生成WebSocket连接类
class LogoGenerationWebSocket {
    private userId: number;
    private socket: WebSocket | null;
    private _isConnected: boolean;
    private reconnectAttempts: number;
    private maxReconnectAttempts: number;
    private reconnectInterval: number;
    private onProgressCallback: ((data: any) => void) | null;
    private onResultCallback: ((data: any) => void) | null;
    private heartbeatInterval: NodeJS.Timeout | null;
    private taskCompleted: boolean;

    constructor(userId: number) {
        this.userId = userId;
        this.socket = null;
        this._isConnected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectInterval = 3000; // 3秒重连间隔
        this.onProgressCallback = null;
        this.onResultCallback = null;
        this.heartbeatInterval = null;
        this.taskCompleted = false;
        
        this.init();
    }
    
    private init(): void {
        this.connect();
    }
    
    private connect(): void {
        try {
            // 建立WebSocket连接
            this.socket = new WebSocket(`ws://localhost:8000/ws/logo-generation/${this.userId}/`);
            
            this.socket.onopen = (event: Event) => {
                console.log('Logo生成WebSocket连接已建立');
                this._isConnected = true;
                this.reconnectAttempts = 0;
                
                // 发送连接确认消息
                this.sendMessage({
                    type: 'ping',
                    timestamp: Date.now()
                });
            };
            
            this.socket.onmessage = (event: MessageEvent) => {
                this.handleMessage(event.data);
            };
            
            this.socket.onclose = (event: CloseEvent) => {
                console.log('Logo生成WebSocket连接已关闭');
                this._isConnected = false;
                this.handleReconnect();
            };
            
            this.socket.onerror = (error: Event) => {
                console.error('Logo生成WebSocket连接错误:', error);
                this._isConnected = false;
            };
            
        } catch (error) {
            console.error('建立WebSocket连接失败:', error);
            this.handleReconnect();
        }
    }
    
    private handleMessage(data: string): void {
        try {
            const message = JSON.parse(data);
            console.log('收到WebSocket消息:', message);
            
            switch (message.type) {
                case 'connection_established':
                    console.log('WebSocket连接已确认');
                    break;
                    
                case 'pong':
                    console.log('收到心跳响应');
                    break;
                    
                case 'logo_progress':
                    if (this.onProgressCallback) {
                        this.onProgressCallback(message.data);
                    }
                    break;
                    
                case 'logo_result':
                    if (this.onResultCallback) {
                        this.onResultCallback(message.data);
                    }
                    break;
                    
                case 'error':
                    console.error('WebSocket错误:', message.message);
                    ElMessage.error(message.message);
                    break;
                    
                default:
                    console.log('未知消息类型:', message.type);
            }
        } catch (error) {
            console.error('解析WebSocket消息失败:', error);
        }
    }
    
    private sendMessage(message: any): void {
        if (this._isConnected && this.socket) {
            this.socket.send(JSON.stringify(message));
        } else {
            console.warn('WebSocket未连接，无法发送消息');
        }
    }
    
    private handleReconnect(): void {
        // 如果任务已完成，不再重连
        if (this.taskCompleted) {
            console.log('Logo生成任务已完成，不再重连WebSocket');
            return;
        }
        
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
            
            setTimeout(() => {
                this.connect();
            }, this.reconnectInterval);
        } else {
            console.error('WebSocket重连失败，已达到最大重试次数');
        }
    }
    
    public disconnect(): void {
        if (this.socket) {
            this.socket.close();
            this.socket = null;
            this._isConnected = false;
        }
    }
    
    // 发送心跳检测
    public startHeartbeat(): void {
        this.heartbeatInterval = setInterval(() => {
            if (this._isConnected) {
                this.sendMessage({
                    type: 'ping',
                    timestamp: Date.now()
                });
            }
        }, 30000); // 每30秒发送一次心跳
    }
    
    public stopHeartbeat(): void {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
    }
    
    // 设置回调函数
    public onProgress(callback: (data: any) => void): void {
        this.onProgressCallback = callback;
    }
    
    public onResult(callback: (data: any) => void): void {
        this.onResultCallback = callback;
    }

    // 获取连接状态
    public get isConnected(): boolean {
        return this._isConnected;
    }
    
    // 标记任务完成
    public markTaskCompleted(): void {
        this.taskCompleted = true;
    }
}

// 定义表单数据类型
interface FormData {
  id?: number
  user_id?: number
  username?: string
  nickname?: string
  avatar?: string
  logo_url?: string
  gender?: string
  birth_date?: string
  height?: number
  weight?: number
  fitness_goal?: string
  fitness_level?: string
  dietary_preference?: string
  activity_level?: string
  has_diabetes?: boolean
  has_hypertension?: boolean
  has_heart_disease?: boolean
  food_allergies?: string
  dietary_restrictions?: string
  preferred_workout_duration?: number
  preferred_workout_times?: number
  created_at?: string
  updated_at?: string
}

export default defineComponent({
  name: 'userProfile_one',
  components: {
    HeaderComponent
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const profileForm = ref<InstanceType<typeof ElForm>>()

    // 状态管理
    const state = reactive({
      formData: {} as FormData,
      formRules: {},
      loading: false,
      logoGenerated: false,
      // WebSocket相关状态
      logoWebSocket: null as LogoGenerationWebSocket | null,
      logoProgress: 0,
      logoStatus: '',
      logoMessage: ''
    })

    // 计算属性 - 根据表单数据计算衍生值
    const ageValue = computed(() => {
      if (!state.formData.birth_date) return null

      const birthDate = new Date(state.formData.birth_date)
      const today = new Date()
      let age = today.getFullYear() - birthDate.getFullYear()
      const monthDiff = today.getMonth() - birthDate.getMonth()

      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--
      }
      return age
    })

    const bmiValue = computed(() => {
      if (!state.formData.height || !state.formData.weight) return null

      const heightInM = Number(state.formData.height) / 100
      const bmi = Number(state.formData.weight) / (heightInM * heightInM)
      return bmi.toFixed(1)
    })

    const bmiCategory = computed(() => {
      if (!bmiValue.value) return null

      const bmi = parseFloat(bmiValue.value)
      if (bmi < 18.5) return "偏瘦"
      if (bmi < 25) return "正常"
      if (bmi < 30) return "超重"
      return "肥胖"
    })

    const bmrValue = computed(() => {
      if (!state.formData.height || !state.formData.weight || !ageValue.value || !state.formData.gender) {
        return null
      }

      // Mifflin-St Jeor公式
      if (state.formData.gender === 'M') {
        return Math.round(
          10 * Number(state.formData.weight) +
          6.25 * Number(state.formData.height) -
          5 * ageValue.value + 5
        )
      } else {
        return Math.round(
          10 * Number(state.formData.weight) +
          6.25 * Number(state.formData.height) -
          5 * ageValue.value - 161
        )
      }
    })

    const tdeeValue = computed(() => {
      if (!bmrValue.value || !state.formData.activity_level) return null

      const multipliers: Record<string, number> = {
        'sedentary': 1.2,
        'light': 1.375,
        'moderate': 1.55,
        'active': 1.725,
        'very_active': 1.9
      }

      return Math.round(bmrValue.value * multipliers[state.formData.activity_level || 'sedentary'])
    })

    const calorieTarget = computed(() => {
      if (!tdeeValue.value || !state.formData.fitness_goal) return null

      switch (state.formData.fitness_goal) {
        case 'weight_loss':
          return tdeeValue.value - 500
        case 'muscle_gain':
          return tdeeValue.value + 300
        default:
          return tdeeValue.value
      }
    })

    // 显示用的计算属性
    const genderDisplay = computed(() => {
      switch (state.formData.gender) {
        case 'M': return '男'
        case 'F': return '女'
        case 'O': return '其他'
        default: return '未设置'
      }
    })

    const fitnessGoalDisplay = computed(() => {
      switch (state.formData.fitness_goal) {
        case 'weight_loss': return '减脂'
        case 'muscle_gain': return '增肌'
        case 'keep_fit': return '保持健康'
        case 'endurance': return '提升耐力'
        default: return '未设置'
      }
    })

    const fitnessLevelDisplay = computed(() => {
      switch (state.formData.fitness_level) {
        case 'beginner': return '新手'
        case 'intermediate': return '进阶'
        case 'advanced': return '专业'
        default: return '未设置'
      }
    })

    const activityLevelDisplay = computed(() => {
      switch (state.formData.activity_level) {
        case 'sedentary': return '久坐(几乎不运动)'
        case 'light': return '轻度活动(每周1-3天运动)'
        case 'moderate': return '中度活动(每周3-5天运动)'
        case 'active': return '积极活动(每周6-7天运动)'
        case 'very_active': return '非常活跃(高强度训练或体力工作)'
        default: return '未设置'
      }
    })

    const dietaryPreferenceDisplay = computed(() => {
      switch (state.formData.dietary_preference) {
        case 'regular': return '普通'
        case 'vegetarian': return '素食'
        case 'vegan': return '纯素'
        case 'low_carb': return '低碳水'
        case 'keto': return '生酮'
        case 'gluten_free': return '无麸质'
        case 'lactose_free': return '无乳糖'
        default: return '未设置'
      }
    })

    const hasDiabetesDisplay = computed(() => {
      return state.formData.has_diabetes ? '是' : '否'
    })

    const hasHypertensionDisplay = computed(() => {
      return state.formData.has_hypertension ? '是' : '否'
    })

    const hasHeartDiseaseDisplay = computed(() => {
      return state.formData.has_heart_disease ? '是' : '否'
    })

    // 页面标题计算属性
    const pageTitle = computed(() => {
      const profileId = route.params.id
      if (profileId) {
        return '用户资料查看'
      } else {
        return '我的资料详情'
      }
    })

    // 判断是否有路由参数的计算属性
    const hasRouteParams = computed(() => {
      return !!route.params.id
    })

    // 获取用户资料详情
    const fetchProfileDetail = () => {
      state.loading = true
      
      // 从localStorage获取当前登录用户信息
      const userInfoStr = localStorage.getItem('userInfo')
      if (!userInfoStr) {
        ElMessage.error('未找到用户信息，请重新登录')
        state.loading = false
        return
      }

      let userInfo
      try {
        userInfo = JSON.parse(userInfoStr)
      } catch (error) {
        ElMessage.error('用户信息格式错误，请重新登录')
        state.loading = false
        return
      }

      const userId = userInfo.user_id
      if (!userId) {
        ElMessage.error('未找到用户ID，请重新登录')
        state.loading = false
        return
      }

      // 获取token并设置请求头
      const token = localStorage.getItem('token')
      const headers = token ? { 'Authorization': `Bearer ${token}` } : {}
      
      // 根据路由参数决定获取方式
      const profileId = route.params.id
      let apiUrl
      
      if (profileId) {
        // 如果有路由参数，使用指定的用户ID（用于管理员查看其他用户）
        apiUrl = `http://localhost:8000/api/profiles/${profileId}/`
      } else {
        // 如果没有路由参数，使用当前登录用户的ID
        apiUrl = `http://localhost:8000/api/profiles/${userId}/`
      }
      
      axios.get(apiUrl, { headers })
        .then(res => {
          if (res.data.success) {
            state.formData = res.data.data
            // 如果用户已有Logo，设置Logo生成状态
            if (res.data.data.logo_url) {
              state.logoGenerated = true
            }
          } else {
            ElMessage.error(res.data.message || '获取用户资料失败')
          }
        })
        .catch(err => {
          ElMessage.error('获取用户资料失败')
          console.error(err)
        })
        .finally(() => {
          state.loading = false
        })
    }

    // 生成专属LOGO
    const generateLogo = (event?: Event) => {
      if (!state.formData.id) {
        ElMessage.error('用户信息不完整，无法生成LOGO')
        return
      }

      // 检查必要的信息
      if (!state.formData.gender || !state.formData.fitness_level) {
        ElMessage.error('请先完善性别和健身水平信息')
        return
      }

      state.loading = true
      state.logoGenerated = true
      state.logoProgress = 0
      state.logoStatus = 'preparing'
      state.logoMessage = '准备生成Logo...'
      
      // 获取token并设置请求头
      const token = localStorage.getItem('token')
      const headers = token ? { 'Authorization': `Bearer ${token}` } : {}
      
      // 准备Logo生成请求数据
      const logoRequest = {
        user_id: state.formData.id,
        gender: state.formData.gender,
        fitness_level: state.formData.fitness_level
      }
      
      // 调用后端Logo生成API（将请求加入队列）
      axios.post(`http://localhost:8000/api/ai/generate-logo/${state.formData.id}/`, logoRequest, { headers })
        .then(res => {
          if (res.data.success) {
            ElMessage.success('Logo生成请求已提交，请等待处理...')
            
            // 确保WebSocket连接已建立
            if (!state.logoWebSocket || !state.logoWebSocket.isConnected) {
              initLogoWebSocket()
            }
          } else {
            state.logoGenerated = false
            state.loading = false
            ElMessage.error(res.data.message || 'LOGO生成请求失败')
          }
        })
        .catch(err => {
          state.logoGenerated = false
          state.loading = false
          console.error('LOGO生成请求错误:', err)
          ElMessage.error('LOGO生成请求失败，请稍后重试')
        })
    }

    // 下载LOGO
    const downloadLogo = () => {
      if (!state.formData.logo_url) {
        ElMessage.error('LOGO地址不存在')
        return
      }

      // 创建一个临时的a标签来下载图片
      const link = document.createElement('a')
      link.href = state.formData.logo_url
      link.download = `专属LOGO_${state.formData.nickname || '用户'}.png`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success('LOGO下载已开始')
    }

    // 初始化Logo WebSocket连接
    const initLogoWebSocket = () => {
      if (!state.formData.id) {
        console.error('[WebSocket] 用户ID不存在，无法建立WebSocket连接')
        return
      }

      console.log(`[WebSocket] 初始化Logo WebSocket连接，用户ID: ${state.formData.id}`)

      // 如果已有连接，先断开
      if (state.logoWebSocket) {
        console.log(`[WebSocket] 断开现有连接，用户ID: ${state.formData.id}`)
        state.logoWebSocket.disconnect()
        state.logoWebSocket.stopHeartbeat()
      }

      // 创建新的WebSocket连接
      state.logoWebSocket = new LogoGenerationWebSocket(state.formData.id)
      
      // 设置进度回调
      state.logoWebSocket.onProgress((data) => {
        console.log(`[WebSocket] 收到进度更新，用户ID: ${state.formData.id}:`, data)
        state.logoProgress = data.progress || 0
        state.logoStatus = data.status || ''
        state.logoMessage = data.message || ''
        
        // 更新UI状态
        if (data.status === 'processing') {
          state.logoStatus = 'processing'
        } else if (data.status === 'generating') {
          state.logoStatus = 'generating'
        }
      })
      
      // 设置结果回调
      state.logoWebSocket.onResult((data) => {
        console.log(`[WebSocket] 收到结果更新，用户ID: ${state.formData.id}:`, data)
        state.loading = false
        
        if (data.success) {
          state.formData.logo_url = data.image_url
          state.logoProgress = 100
          state.logoStatus = 'success'
          state.logoMessage = 'Logo生成成功！'
          ElMessage.success('专属LOGO生成成功！')
          
          // 任务完成，标记任务完成并断开WebSocket连接
          if (state.logoWebSocket) {
            state.logoWebSocket.markTaskCompleted()
            console.log(`[WebSocket] Logo生成完成，断开连接，用户ID: ${state.formData.id}`)
            state.logoWebSocket.disconnect()
            state.logoWebSocket.stopHeartbeat()
          }
        } else {
          state.logoGenerated = false
          state.logoStatus = 'error'
          state.logoMessage = data.message || 'Logo生成失败'
          ElMessage.error(data.message || 'Logo生成失败')
          
          // 错误时也标记任务完成并断开连接
          if (state.logoWebSocket) {
            state.logoWebSocket.markTaskCompleted()
            console.log(`[WebSocket] Logo生成失败，断开连接，用户ID: ${state.formData.id}`)
            state.logoWebSocket.disconnect()
            state.logoWebSocket.stopHeartbeat()
          }
        }
      })
      
      // 启动心跳
      state.logoWebSocket.startHeartbeat()
      
      console.log(`[WebSocket] Logo WebSocket连接初始化完成，用户ID: ${state.formData.id}`)
    }

    // 重新生成LOGO
    const regenerateLogo = () => {
      if (!state.formData.id) {
        ElMessage.error('用户信息不完整，无法重新生成LOGO')
        return
      }

      // 检查必要的信息
      if (!state.formData.gender || !state.formData.fitness_level) {
        ElMessage.error('请先完善性别和健身水平信息')
        return
      }

      state.loading = true
      state.logoGenerated = true
      state.logoProgress = 0
      state.logoStatus = 'preparing'
      state.logoMessage = '准备重新生成Logo...'
      
      // 获取token并设置请求头
      const token = localStorage.getItem('token')
      const headers = token ? { 'Authorization': `Bearer ${token}` } : {}
      
      // 准备Logo生成请求数据
      const logoRequest = {
        user_id: state.formData.id,
        gender: state.formData.gender,
        fitness_level: state.formData.fitness_level
      }
      
      // 调用后端Logo生成API（将请求加入队列）
      axios.post(`http://localhost:8000/api/ai/generate-logo/${state.formData.id}/`, logoRequest, { headers })
        .then(res => {
          if (res.data.success) {
            ElMessage.success('Logo重新生成请求已提交，请等待处理...')
            
            // 确保WebSocket连接已建立
            if (!state.logoWebSocket || !state.logoWebSocket.isConnected) {
              initLogoWebSocket()
            }
          } else {
            state.logoGenerated = false
            state.loading = false
            ElMessage.error(res.data.message || 'LOGO重新生成请求失败')
          }
        })
        .catch(err => {
          state.logoGenerated = false
          state.loading = false
          console.error('LOGO重新生成请求错误:', err)
          ElMessage.error('LOGO重新生成请求失败，请稍后重试')
        })
    }



    // 返回上一页
    const handleBack = () => {
      router.back()
    }

    // 编辑资料
    const handleEdit = () => {
      router.push({
        path: '/user-profile',
        query: { from: 'detail' }
      })
    }

    // 页面加载时获取数据
    onMounted(() => {
      fetchProfileDetail()
    })

    // 页面卸载时清理WebSocket连接
    onUnmounted(() => {
      if (state.logoWebSocket) {
        state.logoWebSocket.stopHeartbeat()
        state.logoWebSocket.disconnect()
      }
    })

    return {
      ...toRefs(state),
      profileForm,
      ageValue,
      bmiValue,
      bmiCategory,
      bmrValue,
      tdeeValue,
      calorieTarget,
      genderDisplay,
      fitnessGoalDisplay,
      fitnessLevelDisplay,
      activityLevelDisplay,
      dietaryPreferenceDisplay,
      hasDiabetesDisplay,
      hasHypertensionDisplay,
      hasHeartDiseaseDisplay,
      pageTitle,
      hasRouteParams,
      fetchProfileDetail,
      generateLogo,
      downloadLogo,
      regenerateLogo,
      initLogoWebSocket,
      handleBack,
      handleEdit
    }
  }
})
</script>

<style scoped>
.user-profile-detail {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.profile-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.info-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.card-header {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.custom-divider {
  color: #409eff;
  font-weight: 600;
}

.custom-divider .el-divider__text {
  background: rgba(255, 255, 255, 0.9);
  padding: 0 15px;
  border-radius: 15px;
}

.form-section-title {
  margin-bottom: 5px;
}

.profile-form {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 20px;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.avatar-container {
  text-align: center;
  margin-bottom: 20px;
}

.user-avatar {
  margin: 0 auto 15px;
}

.calculated-data {
  margin: 20px 0;
  padding: 15px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(5px);
}

.calculated-data p {
  margin: 8px 0;
  font-size: 14px;
}

.logo-container {
  margin-top: 20px;
}

.logo-placeholder {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  color: #606266;
  text-align: center;
  padding: 15px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(5px);
}

.logo-preview {
  text-align: center;
}

.fake-logo {
  width: 120px;
  height: 120px;
  margin: 0 auto;
  background: linear-gradient(135deg, #409eff, #69b1ff);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 48px;
  font-weight: bold;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.logo-desc {
  margin-top: 10px;
  color: #606266;
}

.real-logo {
  width: 120px;
  height: 120px;
  margin: 0 auto;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.logo-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.logo-progress {
  margin: 15px 0;
  padding: 0 10px;
}

.logo-status {
  margin: 10px 0;
  text-align: center;
}

.logo-desc {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
  min-height: 20px;
}
</style>
